package com.qingfeng.util;

import com.alibaba.fastjson.JSONObject;
import com.qingfeng.client.WxConfig;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SignUtil {

    private static int tokenExpiresTime=0;
    private static String accessToken;

    private static int ticketExpiresTime =0;
    private static String jsapiTicket;


    public static void setTokenEmpty(){
        accessToken=null;
    }

    public static String getToken() throws Exception {
        int nowTime = (int) (System.currentTimeMillis()/1000);
        if (tokenExpiresTime==0 || tokenExpiresTime<nowTime || StringUtils.isEmpty(accessToken)){
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WxConfig.APPID + "&secret=" + WxConfig.APPSECRET;
            String result = OkhttpUtil.get(url);
            System.out.println("结果"+result);
            accessToken = JSONObject.parseObject(result).getString("access_token");
            System.out.println("获取微信token "+accessToken);
            tokenExpiresTime = nowTime + 7200;
        }
        return accessToken;
    }
    public static String getTicket() throws Exception {
        int nowTime = (int) (System.currentTimeMillis()/1000);
        if (ticketExpiresTime==0 || ticketExpiresTime<nowTime || StringUtils.isEmpty(jsapiTicket)){
            String access_token = SignUtil.getToken();
            String strUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
            String result = OkhttpUtil.get(strUrl);
            System.out.println(result);
            jsapiTicket = JSONObject.parseObject(result).getString("ticket");
            if (StringUtils.isEmpty(jsapiTicket)) {
                accessToken=null;
                jsapiTicket=null;
                return getTicket();
            }
            ticketExpiresTime = nowTime + 7200;
        }

        return jsapiTicket;
    }

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
